package top.gohigh.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.gohigh.springboot.model.Permission;
import top.gohigh.springboot.model.Role;
import top.gohigh.springboot.service.PermService;
import top.gohigh.springboot.service.RoleService;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController extends BaseController {
    @Autowired
    RoleService roleService;

    @Autowired
    PermService permService;

    @GetMapping("/add/{name}")
    public Role add(@PathVariable String name){
       return roleService.add(name);
    }


    @GetMapping("/addPerms/{id}/{pid}")
    public Role addPerms(@PathVariable Long id,@PathVariable Long pid){


        Role role= roleService.getById(id);
        List<Permission> perms=role.getPermissions();
        if(perms==null){
            perms=new ArrayList<>();
            role.setPermissions(perms);
        }
        perms.add(permService.findById(pid));

        return roleService.update(role);
    }

    @GetMapping("/list/{id}")
    public Role list(@PathVariable Long id){
       return roleService.getById(id);
    }

}
